
import java.util.concurrent.PriorityBlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: fzykd
 * Date: 2022-11-08
 * Time: 23:30
 */
//任务+时间
class MyTask implements Comparable<MyTask> {
    public Runnable runnable;
    public long time;

    public MyTask(Runnable runnable, long after) {
        this.runnable = runnable;
        this.time = after + System.currentTimeMillis();
    }

    @Override
    public int compareTo(MyTask o) {
        return (int) (this.time - o.time);
    }

    //明确一个比较规则

}

class MyTimer {
    //要有一个数据结构来组织
    //带有线程安全的阻塞队列
    PriorityBlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();

    //写一个方法 布置任务
    public void schedule(Runnable runnable,long time){
        MyTask myTask = new MyTask(runnable,time);
        queue.put(myTask);
        //每当有新的任务进来之后 唤醒检查新的任务是否是要先被执行的
        synchronized (locker){
            locker.notify();
        }
    }

    //做一个优化 会出现忙等的问题
    private Object locker = new Object();

    //写一个构造方法 一个单独线程 不断的检查
    public MyTimer(){
        Thread t = new Thread(() -> {
            while (true){
                try {
                    MyTask myTask = queue.take();
                    //做一个判断 如果时间到了那么就执行
                    long newTime = System.currentTimeMillis();
                    if (myTask.time > newTime){
                        //说明时间没到 再次放回到阻塞队列当中
                        queue.put(myTask);
                        //时间没到那么就设定一个等待时间
                        //wait 要配合synchronize使用
                        synchronized (locker){
                            locker.wait(myTask.time - newTime);
                        }
                    }else {
                        myTask.runnable.run();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }


}


//定时器
public class Demo {
    public static void main(String[] args) {

        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello");
            }
        },3000);
    }
}
